import Paho from 'paho-mqtt';

// 存储客户端实例
let client = null;

/**
 * 创建MQTT客户端
 * @param {string} url - MQTT连接的URL（如 'wss://kv.cjhzcn.com:42013/mqtt'）
 * @param {string} clientId - 客户端ID，不传则自动生成
 * @returns {Object} MQTT客户端实例
 */
function createClient(url, clientId = null) {
  // 如果已有客户端连接，先断开
  if (client && client.isConnected()) {
    client.disconnect();
  }

  // 生成默认客户端ID
  const defaultClientId = 'clientId_' + Math.random().toString(16).substr(2, 8);

  // 创建新客户端
  client = new Paho.Client(url, clientId || defaultClientId);

  return client;
}

/**
 * 订阅主题
 * @param {string} topic - 要订阅的主题
 */
function subscribe(topic) {
  if (client && client.isConnected()) {
    client.subscribe(topic);
  } else {
    console.error('MQTT client is not connected');
  }
}

/**
 * 发送消息
 * @param {string} topic - 消息主题
 * @param {string} message - 消息内容
 */
function sendMessage(topic, message) {
  if (client && client.isConnected()) {
    client.send(topic, message);
  } else {
    console.error('MQTT client is not connected');
  }
}

/**
 * 设置消息接收回调
 * @param {Function} callback - 消息接收回调函数
 */
function onMessage(callback) {
  if (client) {
    client.onMessageArrived = callback;
  } else {
    console.error('MQTT client not initialized');
  }
}

/**
 * 连接MQTT服务器
 * @param {Object} options - 连接选项
 * @returns {Promise} 连接结果
 */
function connect(options) {
  if (!client) {
    return Promise.reject(new Error('MQTT client not initialized. Call createClient first.'));
  }

  return new Promise((resolve, reject) => {
    // 设置连接回调
    client.onConnectionLost = (responseObject) => {
      if (responseObject.errorCode !== 0) {
        console.error('Connection lost:', responseObject.errorMessage);
        reject(responseObject);
      }
    };

    // 连接服务器
    client.connect({
      ...options,
      onSuccess: () => {
        console.log('Connected to MQTT server');
        resolve();
      },
      onFailure: (error) => {
        console.error('Connection failed:', error);
        reject(error);
      }
    });
  });
}

/**
 * 断开连接
 */
function disconnect() {
  if (client && client.isConnected()) {
    client.disconnect();
    console.log('Disconnected from MQTT server');
  }
}

export default {
  createClient,    // 创建客户端（动态传入URL）
  connect,         // 连接服务器
  subscribe,       // 订阅主题
  sendMessage,     // 发送消息
  onMessage,       // 设置消息回调
  disconnect,      // 断开连接
  getClient() {    // 获取当前客户端实例
    return client;
  }
};
